<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderException as OrderExceptionService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\CheckclothShrink as CheckclothShrinkService;
use app\common\service\CheckclothShrinkLog as CheckclothShrinkLogService;
use app\common\service\Rejects as RejectsService;
use app\common\service\SystemUser as SystemUserService;
use app\common\service\MaterialReturn as MaterialReturnService;

/**
 * 验布缩水
 *
 */
class CheckclothShrink extends Admin {

	public function initialize() {
		parent::initialize();
	}

	/**
	 * 获取面料列表
	 *
	 * @author KING
	 * @date 2020年7月23日
	 *
	 */
	public function getMaterialList() {
		$clientOrdernum = $this->request->param('client_ordernum/s', '');
		$orderService = new OrderService();
		$orderMaterialService = new OrderMaterialService();
		$orderExceptionService=new OrderExceptionService();
		$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum, 'id');

//		if (!$orderInfo) {
//			return $this->Json(0, "订单号不存在！");
//		}
		$systemUserKV = getSystemUserKV(null);
//		if($orderService->checkExceptionStatus($orderInfo['id'])){
//			$oeList=$orderExceptionService->getStatusListByOrderId($orderInfo['id']);
//			$types= array_column($oeList, 'type');
//			$type="";
//			foreach ($types as $key => $value) {
//				$type=$type.arrayGet(config('mimo.exception_type'), $value,'')."</br>";
//			}
//			return $this->Json(0, "此单异常不允许操作,异常环节有：</br>".$type."请找". arrayGet($systemUserKV,config('mp.order_exception_admin_id'),'邓昆明')."解决");//检查订单是否异常
//		}
        $list = $orderMaterialService->getListByOrderId($orderInfo['id'] ?? 0, ["fabric", "lining"], 'material_id', $clientOrdernum);
        if (empty($list)) {
			return $this->Json(0, "未找到面料信息！");
		}

		$result = $weightList = $widthList = [];
		foreach ($list as $v) {
			$result[$v['mInfo']['id']] = $v['mInfo']['name'] . ' / ' . $v['mInfo']['color'];
			$weightList[$v['mInfo']['id']] = $v['mInfo']['weight'];
			$widthList[$v['mInfo']['id']] = $v['mInfo']['fabric_width'];
			$tube_weight[$v['mInfo']['id']]=$v['mInfo']['customer_weight_page'];
		}

		return $this->Json(1, "拉取成功！", ['list' => $result, 'weightList' => $weightList, 'widthList' => $widthList,'tube_weight'=>$tube_weight]);
	}

	/**
	 * 验布/缩水报表明细
	 *
	 * @author KING
	 * @date 2020年4月28日
	 *
	 */
	public function report() {
		$systemUserKV = getSystemUserKV(null);
		$stallsKV = getStallsKV();
		$factoryKV = getFactoryKV(true);
		$groupKV = getGroupKV(0);
		$checkclothType = config('mimo.checkcloth_type');

		if ($this->request->isAjax()|| $this->request->param('export/d', 0)) {
			$orderService = new OrderService();
			$materialService = new MaterialService();
			$rejectsService = new RejectsService();
			$orderMaterialService = new OrderMaterialService();
			$orderMaterialItemService = new OrderMaterialItemService();
			$checkclothShrinkLogService = new CheckclothShrinkLogService();
			$systemUserService = new SystemUserService();

			// 获取分页参数
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);

			$export     = $this->request->param('export/d', 0);
            $is_return = $this->request->param('is_return/d', 0); //是否退料
			$stallsId   = $this->request->param('stalls_id/d', 0);
			$factoryId   = $this->request->param('factory_id/d', 0);
			$groupId   = $this->request->param('group_id/d', 0);
			$adminId   = $this->request->param('admin_id/d', 0);
			$clientOrdernum   = $this->request->param('client_ordernum/s', '');
			$sku   = $this->request->param('sku/s', 0);
			$createTimeRange   = $this->request->param('create_time_range/s', '');
			$overTimeRange   = $this->request->param('over_time_range/s', '');
			$overType   = $this->request->param('over_type/d', '');
			$type   = $this->request->param('type/d', '');
			$rate   = $this->request->param('rate/d', '');
			$cloName    = $this->request->param('name/s');
            $stock_m_type = $this->request->param('stock_m_type/d', 0);
            $Bmid = $this->request->param('Bmid/s', '');
			$where = [];
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			if ($cloName != '') {
    			$where[] = ['m.name','like', "%".$cloName."%"];
    		}
            if($is_return){
                $is_return=$is_return==2?0:$is_return;
                $where[] = ['cs.is_return', '=', $is_return];
            }
			if($stallsId) $where[] = ['cs.stalls_id', '=', $stallsId];
			if($adminId) $where[] = ['cs.admin_id', '=', $adminId];
			if($clientOrdernum) $where[] = ['cs.client_ordernum', '=', $clientOrdernum];
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $where[] = ['cs.order_id', '=', $temp['id']];
                    }
                    break;
            }
            //订单加一级
            order_level($where,'o.');
			if($overType == 1) $where[] = ['cs.over_time', '=', 0];
			elseif($overType == 2) $where[] = ['cs.over_time', '>', 0];

			if($factoryId) $where[] = ['cs.order_id', 'in', db('order')->where('factory_id', $factoryId)->column('id')];
			if($groupId) $where[] = ['cs.order_id', 'in', db('order')->where('group_id', $groupId)->column('id')];
			if($sku) $where[] = ['cs.order_id', 'in', db('order')->where('sku', 'like', "%".$sku."%")->column('id')];
			if ($overTimeRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $overTimeRange));
				$where[] = ['cs.create_time', 'between', [$startTime, $endTime]];
			}
			if ($type == 3) {
				$where[] = ["cs.type", "=", 1];
				$where[] = ["cs.is_return", "=", 1];
			} else if($type == 4) {
				$where[] = ["cs.type", "=", 2];
				$where[] = ["cs.is_return", "=", 1];
			} elseif($type) {
				$where[] = ["cs.type", "=", $type];
				//$where[] = ["cs.is_return", "=", 0];
			}

			// 克重超标率
			if ($rate == 1) {
				$where[] = ["weight_over", ">", 10];
			}
            if ($stock_m_type > 0) {
                ($stock_m_type - 1) == 0 && $whereType = 0;
                ($stock_m_type - 1) == 1 && $whereType = 1;
                $where[] = ['cs.stock_m_type', '=', $stock_m_type - 1];
            }
            if ($Bmid != '') {
                $where[] = ['cs.order_material_id', '=', substr($Bmid, 1, 10)];
            }

            // 查询数据
            $field = "cs.*,m.name,sa.action_state";
            $total = db('checkcloth_shrink cs')->join('material m', 'm.id = cs.material_id')->join('order o', "cs.order_id=o.id", 'left')->join('stock_action sa', 'cs.stock_action_id=sa.id', 'left')->where($where)->count();
            $list = db('checkcloth_shrink cs')
                ->join('material m', 'm.id = cs.material_id')
                ->join('order o', "cs.order_id=o.id", 'left')
                ->join('stock_action sa', 'cs.stock_action_id=sa.id', 'left')
                ->where($where)->page($page)->field($field)->limit($limit)->order('cs.id desc')->select();
			foreach ($list as $k => $v) {
				$orderId = $v['order_id'];
				$materialId = $v['material_id'];

                if ($v['stock_m_type'] == 0) {
                    $orderInfo = $orderService->getInfoById($orderId);
                    $orderMaterialInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);
                } else {
                    $orderInfo = [];
                    $orderMaterialInfo = $orderMaterialService->getInfoByOrderIdMaterialId(0, 0, '*', $v['order_material_id']);
                }
                if(empty($orderMaterialInfo)){
                    $orderMaterialInfo['tiaoshu']=0;
                    $orderMaterialInfo['mInfo']['name']='';
                    $orderMaterialInfo['mInfo']['color']='';
                    $orderMaterialInfo['caigou_over_time']=0;
                }
				$v['user_name'] = arrayGet($systemUserKV, $v['admin_id'], '');
				$v['role_name'] = $systemUserService->getRoleNameByUserId($v['admin_id']);
				$v['type_name'] = arrayGet(config('mimo.checkcloth_type'), $v['type'], '') . ($v['is_return'] ? '/退料' : '');
				$v['create_time_text'] = $v['create_time'] ? date('Y-m-d H:i', $v['create_time']) : '';
				$v['over_time_text'] = $v['create_time'] ? date('Y-m-d H:i', $v['create_time']) : '';
                $v['caigou_over_time_text'] = $orderMaterialInfo['caigou_over_time'] ? date('Y-m-d H:i', $orderMaterialInfo['caigou_over_time']) : '';
				$field = ($v['type'] == 1) ? 'checkcloth_id' : 'shrink_id';
				$orderMaterialItemInfo = db('order_material_item')->where($field, '=', $v['id'])->findOrEmpty();
				$v['cost_time'] = '';
				if($orderMaterialItemInfo && $orderMaterialInfo['caigou_over_time'] && $orderMaterialInfo['caigou_status']!=2){
                    if($v['over_time']==0) {
                        $v['cost_time'] = formatSecond(time()-$orderMaterialInfo['caigou_over_time']);
                    }else{
                        $v['cost_time'] = formatSecond($v['over_time']-$orderMaterialInfo['caigou_over_time']);
                    }
                }

				$v['stalls_name'] = arrayGet($stallsKV, 'stalls_id', '');
				$v['tiaoshu'] = $orderMaterialInfo['tiaoshu'];

				$v['material_name'] = $orderMaterialInfo['mInfo']['name'];
				$v['color'] = $orderMaterialInfo['mInfo']['color'];
				$v['sku'] = $orderInfo['sku']??'';

				// 横缩率
				$v['length_rate'] = '';
				if ($v['type'] == 2 && $v['length'] > 0 && $v['length_shrink'] > 0) {
					$v['length_rate'] = round($v['length']/$v['length_shrink'], 2);
				}

				// 直缩率
				$v['fabric_width_rate'] = '';
				if ($v['type'] == 2 && $v['fabric_width_shrink'] > 0 && $v['true_fabric_width'] > 0) {
					$v['fabric_width_rate'] = round($v['true_fabric_width']/$v['fabric_width_shrink'], 2);
				}

				$v['rejects_names'] = $rejectsService->getNameStr($v['rejects_ids']);

				if ($v['type'] == 1) {
					$v['weight_shrink'] = '';
					$v['weight_page'] = '';
					$v['true_weight'] = '';
				}
				if (!$v['is_rejects']) {
					$v['rejects_length'] = '';
				}

				$v['is_return_text'] = $v['is_return']?'是':'否';
				$log2 = $checkclothShrinkLogService->getLog($v['id'], 2);
				$v['adjust_remark'] = implode('<br>', array_column($log2, 'remark'));
				$v['adjust_time'] = implode('<br>', array_column($log2, 'create_time_text'));
				$v['adjust_user_name'] = implode('<br>', array_column($log2, 'admin_name'));

				$log1 = $checkclothShrinkLogService->getLog($v['id'], 1);
				$v['edit_remark'] = implode('<br>', array_column($log1, 'remark'));
				$v['edit_time'] = implode('<br>', array_column($log1, 'create_time_text'));
				$v['edit_user_name'] = implode('<br>', array_column($log1, 'admin_name'));

                $v['stock_m_type_txt'] = $v['stock_m_type'] == 0 ? '常规' : '备料';
				$list[$k] = $v;
			}

			// 统计
			$statOver = $statTiaoshu = $statLength = $statLengthShrink = $statWidth = $statWeightShrink = [];
			foreach ($list as $vv) {
				if ($vv['over_time']) $statOver[] = $vv['over_time'];
				$statTiaoshu[] = $vv['tiaoshu'];
				$statLength[] = $vv['length'];
				$statLengthShrink[] = $vv['length_shrink'];
				$statWidth[] = $vv['true_fabric_width'];
				$statWeightShrink[] = $vv['weight_shrink'];
			}

			$items = ['SUM'=>0,'AVG'=>0,'COUNT'=>0,'MAX'=>0,'MIN'=>0];
			$stat = ['over'=>$items,'tiaoshu'=>$items,'length'=>$items,'width'=>$items];
			unset($stat['over']['SUM'], $stat['over']['AVG']);

			$stat['over']['COUNT'] = count($statOver);
			$stat['over']['MAX'] = $statOver && max($statOver) ? date('Y-m-d H:i', max($statOver)) : '';
			$stat['over']['MIN'] = $statOver && min($statOver) ? date('Y-m-d H:i', min($statOver)) : '';

			$stat['tiaoshu']['SUM'] = array_sum($statTiaoshu);
			$stat['tiaoshu']['AVG'] = count($statTiaoshu) ? round(array_sum($statTiaoshu)/count($statTiaoshu)) : 0;
			$stat['tiaoshu']['COUNT'] = count($statTiaoshu);
			$stat['tiaoshu']['MAX'] = $statTiaoshu ? max($statTiaoshu) : 0;
			$stat['tiaoshu']['MIN'] = $statTiaoshu ? min($statTiaoshu) : 0;

			$stat['length']['SUM'] = array_sum($statLength);
			$stat['length']['AVG'] = count($statLength) ? round(array_sum($statLength)/count($statLength)) : 0;
			$stat['length']['COUNT'] = count($statLength);
			$stat['length']['MAX'] = $statLength ? max($statLength) : 0;
			$stat['length']['MIN'] = $statLength ? min($statLength) : 0;

			$stat['length_shrink']['SUM'] = array_sum($statLengthShrink);
			$stat['length_shrink']['AVG'] = count($statLengthShrink) ? round(array_sum($statLengthShrink)/count($statLengthShrink)) : 0;
			$stat['length_shrink']['COUNT'] = count($statLengthShrink);
			$stat['length_shrink']['MAX'] = $statLengthShrink ? max($statLengthShrink) : 0;
			$stat['length_shrink']['MIN'] = $statLengthShrink ? min($statLengthShrink) : 0;

			$stat['width']['SUM'] = array_sum($statWidth);
			$stat['width']['AVG'] = count($statWidth) ? round(array_sum($statWidth)/count($statWidth)) : 0;
			$stat['width']['COUNT'] = count($statWidth);
			$stat['width']['MAX'] = $statWidth ? max($statWidth) : 0;
			$stat['width']['MIN'] = $statWidth ? min($statWidth) : 0;

			$stat['weight_shrink']['SUM'] = array_sum($statWeightShrink);
			$stat['weight_shrink']['AVG'] = count($statWeightShrink) ? round(array_sum($statWeightShrink)/count($statWeightShrink)) : 0;
			$stat['weight_shrink']['COUNT'] = count($statWeightShrink);
			$stat['weight_shrink']['MAX'] = $statWeightShrink ? max($statWeightShrink) : 0;
			$stat['weight_shrink']['MIN'] = $statWeightShrink ? min($statWeightShrink) : 0;
			$data = [];
			$data['data'] = $list;
			//导出
			if ($export) {
				$this->_exportReportXls('验布缩水明细-' .date('YmdHis'), $data['data']);echo 'ok';
				exit;
			}

			$data['stat'] = $stat;
			$data['count'] = $total;
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$adminIds = db('checkcloth_shrink')->distinct(true)->field('admin_id')->column('admin_id');
		foreach ($systemUserKV as $k => $v) {
			if(!in_array($k, $adminIds)) {
				unset($systemUserKV[$k]);
			}
		}

		$assign = [
			'factoryKV' => ['' => '请选择'] + $factoryKV,
			'groupKV' => ['' => '请选择'] + $groupKV,
            'is_return_arr'=>['' => '请选择',1=>'是',2=>'否'],
			'systemUserKV' => ['' => '请选择'] + $systemUserKV,
			'stallsKV' => ['' => '请选择'] + $stallsKV,
			'checkclothTypeKV' => ['' => '请选择'] + $checkclothType,
		];
		return $this->assign($assign)->fetch();
	}
	/**
	 * 缩水明细表导出
	 *
	 * @author King
	 * @date 2020年9月22日
	 *
	 */
	private function _exportReportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				$v['user_name'],
				$v['role_name'],
				$v['type_name'],
				$v['client_ordernum'],
				$v['cloth_num'],
				$v['material_name'],
				$v['color'],
				$v['sku'],
				$v['create_time_text'],
				$v['cost_time'],
				$v['tiaoshu'],
				$v['true_fabric_width']-$v['edge_damage'],
				$v['length'],
				$v['weight_shrink'],
				$v['weight_page'],
				$v['length_shrink'],
				$v['fabric_width_shrink'],
				$v['length_rate'],
				$v['fabric_width_rate'],
				$v['true_weight'],
				$v['weight_over'],
				$v['edge_damage'],
				$v['is_excess'],
				$v['rejects_length'],
				$v['rejects_names'],
				$v['is_return'] == 1 ? '是':'否',


			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['姓名','职能','工序','订单号','布号','布种','颜色','SKU','完成时间','时长','总匹数','实用布封','米长','缩水前重量','纸筒重量','缩前米长','缩前布封','直缩率','横缩率','克重','克重超标','布边损料','用料情况','次品数','次品类型','是否退料'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}
	/**
	 * 产能进度
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 */
	public function progress() {
		$factoryKV = getFactoryKV(true);
		$systemUserKV = getSystemUserKV(null);
		if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factoryId    = $this->request->param('factory_id/d', 0);
			$clientOrdernum    = $this->request->param('client_ordernum/s', '');
			$materialName    = $this->request->param('name/s', '');
			$createDateRange    = $this->request->param('create_date_range/s');
			$export     = $this->request->param('export/d', 0);

			if ($factoryId) {
				$where[] = ['o.factory_id', '=', $factoryId];
			}
			if ($clientOrdernum != '') {
				$where[] = ['omi.client_ordernum', '=', $clientOrdernum];
			}
			if ($clientOrdernum != '') {
				$where[] = ['m.name', 'like', "%".$materialName."%"];
			}
			if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['o.shipment_time', 'between', [$startTime, $endTime+86399]];
			}
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			$count = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->where($where)->count(1);

			$field = 'omi.*,m.name,m.color,o.factory_id,o.shipment_time,om.tiaoshu,om.caigou_status,om.checkcloth_length,om.shrink_length,om.material_dosage,o.caichuang_type';
			$list = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->where($where)->page($page)->limit($limit)->order('omi.create_time desc')->field($field)->select();;

			$stat = ['todayJian'=>0,'toPickNum'=>0,'pickedNum'=>0,'pickedJian'=>0];
			foreach ($list as $k => $v) {
				$list[$k]['seq'] = $count - ($page-1)*$limit - $k;

				if ($v['shrink_length']) {
					$list[$k]['length'] = $v['shrink_length'];
					$list[$k]['type_text'] = '缩水';
					$list[$k]['over_time_text'] = ($v['shrink_time']?date('Y-m-d', $v['shrink_time']):'');
				} else {
					$list[$k]['length'] = $v['checkcloth_length'];
					$list[$k]['type_text'] = '验布';
					$list[$k]['over_time_text'] = ($v['checkcloth_time']?date('Y-m-d', $v['checkcloth_time']):'');
				}
				$list[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$list[$k]['picking_factory_name'] = arrayGet($factoryKV, $v['picking_factory_id'], '');
				$list[$k]['user_name'] = arrayGet($systemUserKV, $v['user_id'], '');
				$list[$k]['picking_time_text'] = ($v['picking_time']?date('Y-m-d', $v['picking_time']):'');
				$list[$k]['create_time_text'] = ($v['create_time']?date('Y-m-d', $v['create_time']):'');
				$list[$k]['shipment_time_text'] = ($v['shipment_time']?date('Y-m-d', $v['shipment_time']):'');

				$list[$k]['jishu'] = $v['material_dosage'] ? round($list[$k]['length']/($v['material_dosage'] * 0.02)) : 0;

				$stat['todayJian'] += $list[$k]['jishu'];
				if ($v['user_id']) {
					$stat['pickedNum'] ++;
					$stat['pickedJian'] += $list[$k]['jishu'];
				} else {
					$stat['toPickNum'] ++;
				}
			}

			$data['data'] = $list;
			//导出
            if($export) {
                $this->_exportXls('产能进度-' .date('YmdHis'), $data['data']);
                exit;
            }
			$data['stat'] = $stat;
			$data['count'] = $count;
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => ['0' => '请选择'] + $factoryKV,
			'pickingUserKV' => ['0' => '请选择'] + getTagUserKV('tag_picking_user'),
		];
		return $this->assign($assign)->fetch();
	}
	/**
	 * 产能进度导出
	 *
	 * @author King
	 * @date 2020年9月22日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				$v['id'],
				date('Y-m-d H:i:s', $v['shipment_time']),
				$v['type_text'],
				$v['client_ordernum'],
				$v['tiaoshu'],
				$v['cloth_num'],
				$v['name'],
				$v['color'],
				date('Y-m-d H:i:s', $v['create_time']),
				$v['caigou_status'] == 1 ? '是':'否',
				$v['length'],
				$v['material_dosage'],
				$v['jishu'],
				$v['over_time_text'],
				$v['factory_name'],
				$v['user_id'] > 0 ? '已领料':'待领料',
				date('Y-m-d H:i:s',$v['picking_time']),
				$v['user_name'],
				$v['caichuang_type'] == 1 ? '手工裁剪':'电脑裁剪',
				$v['picking_factory_name'],
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['序号','出货日期','工序','订单号','总匹数','布号','布种','颜色','到料日期','批色','米长','单件用量','件数','完成时间','分配工厂','领料状态','领料日期','领料人','裁床类别','领料工厂'], // 表头
				'data' => $data,
			],
		];
		plugins_run('excel/excel/export', $params);
	}
	/**
	 * 领料历史
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 * @return array
	 */
	public function history() {
		$factoryKV = getFactoryKV(true);
		$systemUserKV = getSystemUserKV(null);
		if ($this->request->isAjax()) {
			$where      = $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factoryId    = $this->request->param('factory_id/d', 0);
			$clientOrdernum    = $this->request->param('client_ordernum/s', '');
			$materialName    = $this->request->param('name/s', '');

			$where = [
				['omi.user_id', '>', 0]
			];
			if ($factoryId) {
				$where[] = ['o.factory_id', '=', $factoryId];
			}
			if ($clientOrdernum != '') {
				$where[] = ['omi.client_ordernum', '=', $clientOrdernum];
			}
			if ($clientOrdernum != '') {
				$where[] = ['m.name', 'like', "%".$materialName."%"];
			}

			$count = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->where($where)->count(1);

			$field = 'omi.*,m.name,m.color,o.factory_id,o.shipment_time,om.tiaoshu,om.caigou_status,om.checkcloth_length,om.shrink_length,om.material_dosage,o.caichuang_type';
			$list = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->where($where)->page($page)->limit($limit)->order('omi.create_time desc')->field($field)->select();;

			$stat = ['totalJian'=>0];
			foreach ($list as $k => $v) {
				$list[$k]['seq'] = $count - ($page-1)*$limit - $k;

				if ($v['shrink_length']) {
					$list[$k]['length'] = $v['shrink_length'];
					$list[$k]['type_text'] = '缩水';
					$list[$k]['over_time_text'] = ($v['shrink_time']?date('Y-m-d', $v['shrink_time']):'');
				} else {
					$list[$k]['length'] = $v['checkcloth_length'];
					$list[$k]['type_text'] = '验布';
					$list[$k]['over_time_text'] = ($v['checkcloth_time']?date('Y-m-d', $v['checkcloth_time']):'');
				}
				$list[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
				$list[$k]['picking_factory_name'] = arrayGet($factoryKV, $v['picking_factory_id'], '');
				$list[$k]['user_name'] = arrayGet($systemUserKV, $v['user_id'], '');
				$list[$k]['picking_time_text'] = ($v['picking_time']?date('Y-m-d', $v['picking_time']):'');
				$list[$k]['create_time_text'] = ($v['create_time']?date('Y-m-d', $v['create_time']):'');
				$list[$k]['shipment_time_text'] = ($v['shipment_time']?date('Y-m-d', $v['shipment_time']):'');

				$list[$k]['jishu'] = $v['material_dosage'] ? round($list[$k]['length']/($v['material_dosage'] * 0.02)) : 0;

				$stat['totalJian'] += $list[$k]['jishu'];
			}

			$data['data'] = $list;
			$data['stat'] = $stat;
			$data['count'] = $count;
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'factoryKV' => ['0' => '请选择'] + $factoryKV,
			'pickingUserKV' => ['0' => '请选择'] + getTagUserKV('tag_picking_user'),
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 领料
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 */
	public function picking() {
		$systemUserKV = getSystemUserKV(null);
		$pickingFactoryId = $this->request->param('picking_factory_id/d', 1);
		$userId = $this->request->param('user_id/d', 1);
		$id = $this->request->param('id/d', 1);

		$omiInfo = db('order_material_item')->where('id', $id)->findOrEmpty();
		if (empty($omiInfo)) {
			return $this->error('数据异常');
		}

		if (empty($pickingFactoryId)) return $this->error('请选择领料工厂');
		if (empty($userId)) return $this->error('请选择领料人');

		$upData = [
			'picking_factory_id' => $pickingFactoryId,
			'user_id' => $userId,
			'picking_time' => time(),
			'update_time' => time(),
		];
		db('order_material_item')->where('id', $id)->update($upData);

		$this->addOrderLog($omiInfo['order_id'], $omiInfo['client_ordernum'], "用户 ".arrayGet($systemUserKV, $userId, '')." 领取物料 ".getMaterialName($omiInfo['material_id']));
		return $this->Json(1);
	}

	/**
	 * 布号退料
	 *
	 * @author KING
	 * @date 2020年5月11日
	 *
	 */
	public function returnClothNum() {
        $reasonArr  = $this->request->param('reason/a', []);
		$returnLength  = $this->request->param('length/d', 0);
		$mid = $this->request->param('mid/d', 0);	// order_material表ID
		$id = $this->request->param('id/d', 0);		// checkcloth_shrink表ID
		$from = $this->request->param('from/s', '');		// caichuang从裁床发起退料
		$orderService = new OrderService();
		$materialService = new MaterialService();
		$rejectsService = new RejectsService();
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();
		$checkclothShrinkService = new CheckclothShrinkService();
        //$info = $orderMaterialItemService->getInfoById($id);
		$checkclothShrinkInfo = $checkclothShrinkService->getInfoById($id);
		$omInfo = $orderMaterialService->getInfoById($mid);
		if (!$checkclothShrinkInfo || !$omInfo) {
			return $this->Json(0, "验布缩水记录不存在！");
		}
		if ($checkclothShrinkInfo['is_return'] == 1) {
			return $this->Json(0, "该布号已退料！");
		}

		try {
			db()->startTrans();

			$upData = [
				'is_return' => 1,
				'update_admin_id' => ADMIN_ID,
				'update_time' => time(),
			];
			db('checkcloth_shrink')->where('id', $id)->update($upData);

			// 标记退料
			$omiData = [
				'is_return' => 1,
				'action_time' => time(),
				'update_time' => time()
			];
			db('order_material_item')->where('order_material_id', $mid)->where('cloth_num', $checkclothShrinkInfo['cloth_num'])->update($omiData);

			$orderId = $checkclothShrinkInfo['order_id'];
			$materialId = $checkclothShrinkInfo['material_id'];

			// 扣除条数(20200928修改为在 退料进度 确认退料后扣除条数)
			/* if ($omInfo && $omInfo['tiaoshu'] > 0) {
				$omData = [
					'tiaoshu' => $omInfo['tiaoshu']-1,
					'shiji_caigou_count' => $omInfo['tiaoshu']-1,
					'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
				];
				db('order_material')->where('mid', $omInfo['mid'])->update($omData);
			} */
//            $orderMaterialService->material_return_update($mid);

			//同步到采购备忘
			$materialName = $materialService->getMaterialName($materialId);
			$memoData = [
				'order_id' => $orderId,
				'client_ordernum' => $checkclothShrinkInfo['client_ordernum'],
				'content' => "物料[".$materialName."]布号[{$checkclothShrinkInfo['cloth_num']}]退料",
				'status' => 0,
				'create_time' => time(),
				'update_time' => time(),
			];
			db('memo')->insertGetId($memoData);

			// 同步到退料进度表里
			$mrData = [
				'material_id' => $checkclothShrinkInfo['material_id'],
				'order_id' => $checkclothShrinkInfo['order_id'],
				'client_ordernum' => $checkclothShrinkInfo['client_ordernum'],
				'order_material_id' => $mid,
				'order_material_item_id' => $checkclothShrinkInfo['order_material_item_id'],
				'cloth_num' => $checkclothShrinkInfo['cloth_num'],
				'return_length' => $returnLength,
				'type' => 1,
				'reason' => implode(',', $reasonArr),
				'admin_id' => ADMIN_ID,
				'status' => 0,
				'is_reduce' => 0,
				'create_time' => time(),
				'update_time' => time(),
			];
			$materialReturnId = db('material_return')->insertGetId($mrData);

			// 记录退料操作日志
			(new MaterialReturnService())->addLog($materialReturnId, 1);

			// 同步数据
			$checkclothShrinkService->syncData($orderId, $materialId, 0);
			$orderMaterialService->updateCaichuangStatusV2($checkclothShrinkInfo['order_id'],$mid);
			// 重新计算唛架信息
			if ($from == 'caichuang') {
				$orderMaterialService->resetWheatData($mid);
			}

			// 记录订单日志
			$this->addOrderLog($orderId, $checkclothShrinkInfo['client_ordernum'], $memoData['content']);
			db()->commit();
			return $this->Json(1, "布号{$checkclothShrinkInfo['cloth_num']}退料成功");
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	/**
	 * 编辑
	 *
	 * @author KING
	 * @date 2020年5月11日
	 *
	 */
	public function edit() {
		$systemUserKV = getSystemUserKV(null);
		$id = $this->request->param('id/d', 0);
		$checkclothShrinkService = new CheckclothShrinkService();
		$orderMaterialItemService = new OrderMaterialItemService();
		$materialService = new MaterialService();

		$checkclothShrinkInfo = $checkclothShrinkService->getInfoById($id);
		$checkclothShrinkField = (arrayGet($checkclothShrinkInfo, 'type', 0) == 1) ? 'checkcloth_id':'shrink_id';
		$orderMaterialItemInfo = db('order_material_item')->where($checkclothShrinkField, $id)->findOrEmpty();
		if (!$checkclothShrinkInfo || !$orderMaterialItemInfo) {
			return $this->Json(0, "验布缩水记录不存在！");
		}
		if ($this->request->isAjax()) {

			try {
				db()->startTrans();

				$post = $this->request->param();
				$csUpData = [
					'update_admin_id' => ADMIN_ID,
					'update_time' => time(),
				];

				$log1 = [];
				$log2 = [];

				// 检测材料和布号是否已经过缩水验布处理了
				$csInfo = db('checkcloth_shrink')->where("type = {$checkclothShrinkInfo['type']} and order_id = {$checkclothShrinkInfo['order_id']} and material_id = {$post['material_id']} and cloth_num = {$post['cloth_num']} and id != {$id}")->findOrEmpty();
				if ($csInfo) {
					return $this->Json(0, "对应材料的布号已进行过缩水或验布处理，修改失败！(error:001)");
				}
				$omiInfo = db('order_material_item')->where("order_id = {$checkclothShrinkInfo['order_id']} and material_id = {$post['material_id']} and cloth_num = {$post['cloth_num']}")->findOrEmpty();
				if (!$omiInfo) {
					return $this->Json(0, "对应材料的布号不存在！");
				}
				if ($omiInfo[$checkclothShrinkField] > 0 && $omiInfo[$checkclothShrinkField] != $id) {
					return $this->Json(0, "对应材料的布号已进行过缩水或验布处理，修改失败！(error:002)");
				}

				$materialInfo = $materialService->getInfoById($checkclothShrinkInfo['material_id']);
				$omiUpdata = [];
				if ($checkclothShrinkInfo['material_id'] != $post['material_id']) {
					$csUpData['material_id'] = $post['material_id'];
					$omiUpdata['material_id'] = $post['material_id'];
					$log1[] = "原材料".$materialInfo['name'];
				}
				if ($checkclothShrinkInfo['cloth_num'] != $post['cloth_num']) {
					$csUpData['cloth_num'] = $post['cloth_num'];
					$omiUpdata['cloth_num'] = $post['cloth_num'];
					$log1[] = "原布号".$checkclothShrinkInfo['cloth_num'];
				}

				if (isset($post['admin_id']) && $post['admin_id'] != $checkclothShrinkInfo['admin_id']) { // 操作人有修改
					$csUpData['admin_id'] = $post['admin_id'];
					$csUpData['ori_admin_id'] = $checkclothShrinkInfo['admin_id'];
					$log2[] = "原操作员".arrayGet($systemUserKV, $checkclothShrinkInfo['admin_id']);
				}

				$field = 'weight_shrink';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原缩前重量".$checkclothShrinkInfo[$field];
				}
				$field = 'weight_page';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原纸筒重量".$checkclothShrinkInfo[$field];
				}
				$field = 'true_fabric_width';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原实量幅宽".$checkclothShrinkInfo[$field];
				}
				$field = 'edge_damage';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原布边损料".$checkclothShrinkInfo[$field];
				}
				$field = 'cc_length';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo['length']) {
					$csUpData['length'] = $post[$field];
					$log1[] = "原验布米长".$checkclothShrinkInfo['length'];
				}
				$field = 'length';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原缩水米长".$checkclothShrinkInfo[$field];
				}
				$field = 'rejects_length';
				if (isset($post[$field]) && $post[$field] != $checkclothShrinkInfo[$field]) {
					$csUpData[$field] = $post[$field];
					$log1[] = "原次品米长".$checkclothShrinkInfo[$field];
				}
				$csUpData['rejects_ids'] = isset($post['rejects_id']) && $post['rejects_id'] ? implode(',', $post['rejects_id']) : '';

				db('checkcloth_shrink')->where('id', $id)->update($csUpData);

				// 需要处理旧的为未处理
				if ($omiUpdata) {
					// 重置原有的
					$resetData = [
						$checkclothShrinkField => 0,
						'is_return' => 0,
					];
					if($checkclothShrinkInfo['type'] == 1) {
						$resetData['is_checkcloth'] = 0;
						$resetData['checkcloth_time'] = 0;
					} elseif($checkclothShrinkInfo['type'] == 2) {
						$resetData['is_shrink'] = 0;
						$resetData['shrink_time'] = 0;
					}
					db('order_material_item')->where($checkclothShrinkField, $id)->update($resetData);

					$newData = [
						$checkclothShrinkField => $id,
						'is_return' => $checkclothShrinkInfo['is_return'],
					];
					if($checkclothShrinkInfo['type'] == 1) {
						$newData['is_checkcloth'] = 1;
						$newData['checkcloth_time'] = $checkclothShrinkInfo['create_time'];
					} elseif ($checkclothShrinkInfo['type'] == 2) {
						$newData['is_shrink'] = 1;
						$newData['shrink_time'] = $checkclothShrinkInfo['create_time'];
					}
					db('order_material_item')->where("order_id = {$checkclothShrinkInfo['order_id']} and material_id = {$post['material_id']} and cloth_num = {$post['cloth_num']}")->update($newData);

					// 同步每条布米长
					$orderMaterialItemService->updateLength($checkclothShrinkInfo['order_id'], $checkclothShrinkInfo['material_id']);
					if($checkclothShrinkInfo['material_id'] != $post['material_id']) $orderMaterialItemService->updateLength($checkclothShrinkInfo['order_id'], $post['material_id']);
				}

				if ($log1) {
					$logData = [
						'checkcloth_shrink_id' => $id,
						'type' => 1,
						'remark' => implode('<br>', $log1),
						'admin_id' => ADMIN_ID,
						'create_time' => time(),
					];
					db('checkcloth_shrink_log')->insertGetId($logData);
				}
				if ($log2) {
					$logData = [
						'checkcloth_shrink_id' => $id,
						'type' => 2,
						'remark' => implode('<br>', $log2),
						'admin_id' => ADMIN_ID,
						'create_time' => time(),
					];
					db('checkcloth_shrink_log')->insertGetId($logData);
				}

				// 需再次同步数据
				$checkclothShrinkService->syncData($checkclothShrinkInfo['order_id'], $checkclothShrinkInfo['material_id'], 0);
				if ($checkclothShrinkInfo['material_id'] != $post['material_id']) {
					$checkclothShrinkService->syncData($checkclothShrinkInfo['order_id'], $post['material_id'], 0);
				}

				$this->addOrderLog($checkclothShrinkInfo['order_id'], $checkclothShrinkInfo['client_ordernum'], "编辑验布缩水记录ID {$id}，".implode('，', $log1));
				db()->commit();
				return $this->Json(1, "操作成功");
			} catch (\Exception $e) {
				db()->rollback();
				return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
			}
		}

		// 材料列表
		$materialIdArr = db('order_material_item')->where("order_id = {$checkclothShrinkInfo['order_id']}")->distinct(true)->field('material_id')->column("material_id");
		$assign = [
			'materialList' => db('material')->where('id', 'in', $materialIdArr)->column('name', 'id'),
			'rejectsKV' => getRejectsKV(),
			'formData' => $checkclothShrinkInfo,
			'checkclothShrinkUserKV' => getRoleUserKV('role_id_checkcloth') + getRoleUserKV('role_id_shrink') + getRoleUserKV('role_id_checkclothshrink')
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * 获取布号
	 *
	 * @author KING
	 * @date 2020年4月24日
	 *
	 */
	public function getClothNum() {
		/* $clientOrdernum = $this->request->param('client_ordernum/s', '');
		$materialId = $this->request->param('material_id/d', 0);

		$orderService = new OrderService();
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();

		$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum, 'id');
		if (!$orderInfo) {
			return $this->Json(0, "订单号不存在！");
		}

		if (empty($materialId)) {
			return $this->Json(0, "未选择面料！");
		}

		$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderInfo['id'], $materialId, 'mid');
		if (empty($omInfo)) {
			return $this->Json(0, "材料数据异常！");
		}

		$list = $orderMaterialItemService->getClothNumList($orderInfo['id'], $materialId, 1);
		return $this->Json(1, "获取成功！", $list); */
	}

	/**
	 * 已验布或缩水的明细（裁床进度调用）
	 *
	 * @author KING
	 * @date 2020年5月12日
	 *
	 */
	public function showLog() {
		$type = $this->request->param('type');	// 类型（1验布，2缩水）
		$orderMaterialId = $this->request->param('order_material_id/d', 0);

		if ($this->request->isAjax()) {

			$orderMaterialService = new OrderMaterialService();
			$omInfo = $orderMaterialService->getInfoById($orderMaterialId);

	        $where = [
	        	['order_id', '=', arrayGet($omInfo, 'order_id', 0)],
	        	['material_id', '=', arrayGet($omInfo, 'material_id', 0)],
	        	['is_return', '=', 0],
	        	['type', '=', $type],
	        ];
	        $total = db('checkcloth_shrink')->where($where)->count(1);
	        $list = db('checkcloth_shrink')->where($where)->order('id desc')->select();
	        foreach ($list as $k => $v) {
	        	$isFromStock = db('order_material_item')->where('id', $v['order_material_item_id'])->value('is_from_stock', 0);

	        	$str = '';
	        	if (!empty($v['is_excess'])){
	        		$str = '多料';
	        	}
	        	if (!empty($isFromStock)){
	        		$str = '库存';
	        	}
	        	if (!empty($v['is_excess']) && !empty($isFromStock)){
	        		$str = '多料+库存';
	        	}
	        	$list[$k]['text_desc'] = $str;
	        }

	        $data['data'] = $list;
	        $data['count'] = $total;
	        $data['code'] = 0;
	        $data['msg'] = '';
	        return json($data);
		}

		$assign = [
			'type' => $type,
			'orderMaterialId' => $orderMaterialId
		];
        return $this->assign($assign)->fetch();
	}

	/**
	 * 验布缩水考核统计
	 *
	 * @author KING
	 * @date 2020年6月11日
	 *
	 * 已知 5月5日 验布数据：
		A = 5月5日来料需验布总条数
		B = 5月5日来料需验布总条数中 验布员张三 验完的条数（含退料）
		C = 5月5日来料需验布总条数中 未验完的总条数
		D = 5月5日验布员张三 验完的总条数（含5月5日之前的来料，含退料）
		E = 5月5日所有验布员（不含组长）验完的总条数（含5月5日之前的来料，含退料）
		F = 5月5日组长验布总条数

		求 5月5日 张三 验布 考核数据
		X = 5月5日任务总数 = D + (D/E)*F + (D/E)*C
		Y = 5月5日完成总数 = D
		Z = 5月5日未完成总数 = X - Y
	 */
	public function kpi() {
		if ($this->request->isAjax()) {
			$type = $this->request->param('type');
			$adminId = $this->request->param('admin_id');
			$createDateRange = $this->request->param('create_date_range');
			// $export = $this->input->post('export');

			$searchType = ($type == 1 || $type == 2) ? $type : 0;

			$endTime = strtotime(date('Y-m-d 00:00:00'));
			$startTime = $endTime-10*86400;
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
			}

			if ($startTime < strtotime(date('2020-06-1 00:00:00'))) $startTime = strtotime(date('Y-m-1 00:00:00'));

			// 组长ID
			$uidArr = array_keys(getRoleUserKV('role_id_checkclothshrink'));

			$result = [];
			for($dayTime = $startTime; $dayTime <= $endTime; $dayTime=$dayTime+86400) {
				$dayTimeEnd = $dayTime +86400-1;

				if (in_array($searchType, [0, 1])) {	// 验布
					$result = array_merge($result, $this->_kpiStat(1, $dayTime, $dayTimeEnd, $uidArr, $adminId));
				}

				if (in_array($searchType, [0, 2])) {	// 缩水
					$result = array_merge($result, $this->_kpiStat(2, $dayTime, $dayTimeEnd, $uidArr, $adminId));
				}
			}

			/* if ($export > 0) {
				$xlsData = [];
				$titleArr = ['','姓名','职能','工序','完成日期','任务总数（条）','完成总数（条）','未完成总数（条）','完成率','幅宽总数','幅宽差异统计','准确率（幅宽）','米长总数','米长差异统计','准确率（米长）','综合达标率（平均）'];
				unset($titleArr[0]);
				$xlsData[0] = $titleArr;

				$j=1;
				foreach ($result as $k => $v) {
					$val = [
						'',
						$v['userName'],
						$v['userRole'],
						$v['typeName'],
						$v['date'],
						$v['taskTotal'],
						$v['overTotal'],
						$v['unOverTotal'],
						$v['overRate'].'%',
						$v['widthTotal'],
						$v['widthDiffTotal'],
						$v['widthRate'].'%',
						$v['lengthTotal'],
						$v['lengthDiffTotal'],
						$v['lengthRate'].'%',
						$v['standardRate'].'%',
					];
					unset($val[0]);
					$xlsData[$j] = $val;
					$j++;
				}
				$this->_saveExcel($xlsData, '验布缩水考核');
			} */

			$data = [];
			$data['data'] = $result;
			$data['count'] = count($result);
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$adminIdArr = db('checkcloth_shrink')->distinct(true)->field('admin_id')->column('admin_id');
		$checkclothShrinkUserKV = db('system_user')->where('id', 'in', $adminIdArr)->column('nick', 'id');
		$assign = [
			'checkclothShrinkUserKV' => ['' => '请选择'] + $checkclothShrinkUserKV,
			'typeArr' => ['' => '请选择'] + ['1'=>'验布','2'=>'缩水'],
		];
		return $this->assign($assign)->fetch();
	}

	/**
	 * kpi数据统计计算
	 *
	 * @author KING
	 * @date 2020年6月28日
	 *
	 * @param integer $type				类型（1验布，2缩水）
	 * @param integer $dayTime
	 * @param integer $dayTimeEnd
	 * @param array $uidArr
	 * @param integer $adminId
	 * @return array
	 */
	private function _kpiStat($type, $dayTime, $dayTimeEnd, $uidArr, $adminId) {
		if ($type == 1) {
			$typeWhere = "cs.type = 1";
			$needWhere = "omi.need_checkcloth = 1";
			$isWhere = "omi.is_checkcloth = 1";	// 验布
			$actionTimeField = "omi.checkcloth_time";
			$checkClothShrinkIdField = "omi.checkcloth_id";
			$typeName = "验布";
		} else {
			$typeWhere = "cs.type = 2";
			$needWhere = "omi.need_shrink = 1";
			$isWhere = "omi.is_shrink = 1";	// 缩水
			$actionTimeField = "omi.shrink_time";
			$checkClothShrinkIdField = "omi.shrink_id";
			$typeName = "缩水";
		}

		$result = [];
		// A当天所有来料需验布条数
		$where = [
			['omi.create_time', 'between', [$dayTime, $dayTimeEnd]]
		];
		$needCheckClothNumToday = db('order_material_item omi')->where($needWhere)->where($where)->count(1);

		// C当天来料需验布总条数中 未验完的总条数
		$where = [
			['omi.create_time', 'between', [$dayTime, $dayTimeEnd]],
		];
		$unCheckClothNumToday = db('order_material_item omi')->where($needWhere)->where($where)->where("{$actionTimeField} = 0 or {$actionTimeField} > {$dayTimeEnd}")->count(1);

		// E当天所有验布员（不含组长）验完的总条数（含之前的来料，含退料）
		$where = [
			['cs.create_time', 'between', [$dayTime, $dayTimeEnd]],
		];
		if ($uidArr) $where[] = ["cs.admin_id", "not in", $uidArr];
		$unCheckClothNumTotal = db('checkcloth_shrink cs')->where($typeWhere)->where($where)->count(1);

		// F组长验布总条数
		$checkClothNumLead = 0;
		if ($uidArr) {
			$where = [
				['cs.create_time', 'between', [$dayTime, $dayTimeEnd]],
				['cs.admin_id', 'in', $uidArr]
			];
			$checkClothNumLead = db('checkcloth_shrink cs')->where($typeWhere)->where($where)->count(1);
		}

		// 获取当日的验布人员
		$where = [
			['cs.create_time', 'between', [$dayTime, $dayTimeEnd]],
		];
		if ($uidArr) $where[] = ["cs.admin_id", "not in", $uidArr];
		if ($adminId) $where[] = ["cs.admin_id", "=", $adminId];
		$userList = db('checkcloth_shrink cs')->where($typeWhere)->where($where)->distinct(true)->field('cs.admin_id')->select();

		$systemUserService = new SystemUserService();
		$systemUserKV = getSystemUserKV(null);
		foreach ($userList as $sv) {
			$uid = $sv['admin_id'];

			// B当天来料需验布总条数中 验布员$uid 验完的条数（含退料）
			$where = [
				['cs.admin_id', '=', $uid],
				['omi.create_time', 'between', [$dayTime, $dayTimeEnd]]
			];
			$uidCheckClothNumToday = db('order_material_item omi')->join('checkcloth_shrink cs', "cs.id = {$checkClothShrinkIdField}")->where($where)->count(1);

			// D验布员$uid 验完的总条数（含之前日期的来料，含退料）
			$where = [
				['cs.admin_id', '=', $uid],
				['cs.create_time', 'between', [$dayTime, $dayTimeEnd]]
			];
			if ($type == 1) {
				$uidCheckClothNumTotal = db('checkcloth_shrink cs')->where($typeWhere)->where($where)->count(1);
			} else {
				/*缩水的面料数据进入“考核列表”再加两个条件：
				1、标记为验布的：验布+批色后进入“考核列表”；
				2、标记为不验布的：打标+批色后进入“考核列表”；*/
				$uidCheckClothNumTotal = db('checkcloth_shrink cs')
				->join('order_material_item omi', 'omi.id=cs.order_material_item_id')
				->join('order_material om', 'om.mid=omi.order_material_id')
				->where($typeWhere)->where($where)
				->where("om.caigou_status=1 and (omi.need_checkcloth=1 and omi.is_checkcloth=1 or omi.need_checkcloth=0 and om.is_make_tag=1)")
				->count(1);
			}

			// 幅宽总数=完成订单数
			$where = [
				['cs.is_return', '=', 0],
				['cs.admin_id', '=', $uid],
				['cs.create_time', 'between', [$dayTime, $dayTimeEnd]]
			];
			$widthTotal = db('checkcloth_shrink cs')
			->where($typeWhere)->where($where)->distinct(true)->field('cs.order_id')->count(1);

			// 幅宽差异统计
			$where = [
				['omi.is_return', '=', 0],
				['cs.admin_id', '=', $uid],
				[$actionTimeField, 'between', [$dayTime, $dayTimeEnd]],
			];
			$subQuery = db('order_material_item omi')
				->join('checkcloth_shrink cs', "cs.id = {$checkClothShrinkIdField}")
				->join('order_material om', "om.mid = omi.order_material_id")
				->where($isWhere)
				->where($where)
				->group('omi.order_id')
				->fieldRaw('abs(min(cs.true_fabric_width) - om.caichuang_fabric_width) as diff')
				->buildSql();
			$widthDiffTotal = db()->table($subQuery . ' tb')->where('diff', '>', 1)->count(1);

			// 米长总数
			$where = [
				['omi.is_return', '=', 0],
				['cs.admin_id', '=', $uid],
				[$actionTimeField, 'between', [$dayTime, $dayTimeEnd]],
			];
			$lengthTotal = db('order_material_item omi')
			->join('checkcloth_shrink cs', "cs.id = {$checkClothShrinkIdField}")
			->where($isWhere)->where($where)->sum('cs.length');

			// 米长差异统计
			$where = [
				['omi.is_return', '=', 0],
				['cs.admin_id', '=', $uid],
				[$actionTimeField, 'between', [$dayTime, $dayTimeEnd]],
			];
			$subQuery1 = db('order_material_item omi')
			->join('checkcloth_shrink cs', "cs.id = {$checkClothShrinkIdField}")
			->join('order_material om', "om.mid = omi.order_material_id")
			->where($isWhere)
			->where($where)
			->group('omi.order_id')
			->fieldRaw('sum(cs.length) as length, if(om.caichuang_dosage>0,om.caichuang_dosage,0) as dosage')
			->buildSql();
			$subQuery2 = db()->table($subQuery1 . ' tb')->fieldRaw('if(dosage>0, abs(length-dosage)*100/dosage, length) as diff')->buildSql();
			$lengthDiffTotal = db()->table($subQuery2 . ' tb2')->where('diff', '>', 5)->count(1);

			// X任务总数 = D + (D/E)*F + (D/E)*C;
			if ($unCheckClothNumTotal) {
				$taskTotal = $uidCheckClothNumTotal + ($uidCheckClothNumTotal/$unCheckClothNumTotal)*$checkClothNumLead + ($uidCheckClothNumTotal/$unCheckClothNumTotal)*$unCheckClothNumToday;
				$taskTotal = round($taskTotal);
			} else $taskTotal = $uidCheckClothNumTotal;

			// Y完成总数 = D
			$overTotal = $uidCheckClothNumTotal;

			// Z未完成总数 = X - Y
			$unOverTotal = $taskTotal - $overTotal;

			$item = [
				'uid' => $uid,
				'userName' => arrayGet($systemUserKV, $uid, ''),
				'userRole' => $systemUserService->getRoleNameByUserId($uid),
				'date' => date('Y-m-d', $dayTime),
				'type' => $type,
				'typeName' => $typeName,
				'taskTotal' => $taskTotal,			// 任务总数
				'overTotal' => $overTotal,			// 完成数
				'unOverTotal' => $unOverTotal,		// 未完成数
				'overRate' => $taskTotal == 0 ? '0' : round(100*$overTotal/$taskTotal),	// 完成率
				'widthTotal' => $widthTotal,	// 幅宽总数
				'widthDiffTotal' => $widthDiffTotal,	// 幅宽差异统计
				'widthRate' => ($widthTotal ? round((1-$widthDiffTotal/$widthTotal)*100) : 0),	// 准确率（幅宽）
				'lengthTotal' => round($lengthTotal),	// 米长总数
				'lengthDiffTotal' => $lengthDiffTotal,	// 米长差异统计
				'lengthRate' => ($lengthTotal ? round((1-$lengthDiffTotal/$lengthTotal)*100) : 0),	// 准确率（米长）
				'standardRate' => '0',	// 综合达标率（平均）
			];
			$synthesizeRate = array_sum([$item['overRate'], $item['widthRate'], $item['lengthRate']]);

			$item['standardRate'] = $synthesizeRate > 0 ? round($synthesizeRate/3) : 0;	// 综合达标率（平均）
			$result[] = $item;
		} // end $userList
		return $result;
	}

	/**
	 * kpi详情
	 *
	 * @author KING
	 * @date 2020年6月28日
	 *
	 */
	public function kpiDetail() {
		$uid = $this->request->param('uid/d', 0);
		$type = $this->request->param('type/d', 0);
		$date = $this->request->param('date/s', '');
		if ($this->request->isAjax()) {
			$systemUserService = new SystemUserService();
			$systemUserKV = getSystemUserKV(null);

			if ($type == 1) {
				$typeWhere = "cs.type = 1";
				$needWhere = "omi.need_checkcloth = 1";
				$isWhere = "omi.is_checkcloth = 1";	// 验布
				$actionTimeField = "omi.checkcloth_time";
				$checkClothShrinkIdField = "omi.checkcloth_id";
				$typeName = "验布";
			} else {
				$typeWhere = "cs.type = 2";
				$needWhere = "omi.need_shrink = 1";
				$isWhere = "omi.is_shrink = 1";	// 缩水
				/*缩水的面料数据进入“考核列表”再加两个条件：
				 1、标记为验布的：验布+批色后进入“考核列表”；
				 2、标记为不验布的：打标+批色后进入“考核列表”；*/
				$isWhere .=" and om.caigou_status=1 and (omi.need_checkcloth=1 and omi.is_checkcloth=1 or omi.need_checkcloth=0 and om.is_make_tag=1)";

				$actionTimeField = "omi.shrink_time";
				$checkClothShrinkIdField = "omi.shrink_id";
				$typeName = "缩水";
			}

			$dayTime = strtotime($date.' 00:00:00');
			$dayTimeEnd = $dayTime + 86400-1;

			$where = [
				['omi.is_return', '=', 0],
				['cs.admin_id', '=', $uid],
				[$actionTimeField, 'between', [$dayTime, $dayTimeEnd]],
			];
			$list = db('order_material_item omi')
				->join('material m', 'm.id = omi.material_id')
				->join('checkcloth_shrink cs', "cs.id = {$checkClothShrinkIdField}")
				->join('order_material om', 'om.mid = omi.order_material_id')
				->where($where)
				->where($isWhere)
				->fieldRaw('omi.client_ordernum,omi.cloth_num,m.name,m.color,cs.true_fabric_width,cs.length,om.caichuang_fabric_width,om.caichuang_dosage')
				->select();
			$result = [];
			foreach ($list as $k => $v) {
				if (!array_key_exists($v['client_ordernum'], $result)) {
					$result[$v['client_ordernum']] = [
						'userName' => arrayGet($systemUserKV, $uid, ''),
						'userRole' => $systemUserService->getRoleNameByUserId($uid),
						'typeName' => $typeName,
						'clientOrdernum' => $v['client_ordernum'],
						'caichuangFabricWidth' => round($v['caichuang_fabric_width'], 2),
						'caichuangDosage' => round($v['caichuang_dosage'], 2),
					];
				}
				$result[$v['client_ordernum']]['list'][] = $v;
			}
			foreach ($result as $k => $v) {
				$result[$k]['trueFabricWidth'] = min(array_column($v['list'], 'true_fabric_width'));
				$result[$k]['length'] = array_sum(array_column($v['list'], 'length'));
				$result[$k]['trueFabricWidthDiff'] = round(abs($result[$k]['trueFabricWidth'] - $result[$k]['caichuangFabricWidth']), 2);

				if ($result[$k]['caichuangDosage']) {
					$result[$k]['lengthDiff'] = round(abs($result[$k]['length']-$result[$k]['caichuangDosage']) * 100 / $result[$k]['caichuangDosage'], 2);
				} else {
					$result[$k]['lengthDiff'] = round($result[$k]['length'], 2);
				}

			}

			$data = [];
			$data['data'] = $result;
			$data['count'] = count($result);
			$data['code'] = 0;
			$data['msg'] = '';
			return json($data);
		}

		$assign = [
			'uid' => $uid,
			'type' => $type,
			'date' => $date,
		];
		return $this->assign($assign)->fetch();
	}

}

